//
//  FPLoginController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/3/31.
//

#import "FPLoginController.h"
#import "FPForgetPasswordController.h"
#import "FPSetPasswordController.h"

@interface FPLoginController () <UITextFieldDelegate , TTTAttributedLabelDelegate>

@property (nonatomic , assign) BOOL isSelect;
@property (nonatomic , strong) JBubbleTips *bubbleTip;
@property (weak, nonatomic) IBOutlet UIImageView *selectImgView;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *privacyLab;
@property (weak, nonatomic) IBOutlet UILabel *errorTipPhoneLab;
@property (weak, nonatomic) IBOutlet UILabel *errorTipPwdLab;

// 一键登录 view
@property (weak, nonatomic) IBOutlet UIView *autoLoginBackView;
@property (weak, nonatomic) IBOutlet UIButton *autoLoginBtn;
@property (weak, nonatomic) IBOutlet UILabel *numberLab;
@property (weak, nonatomic) IBOutlet UILabel *serviceLab;
@property (weak, nonatomic) IBOutlet UILabel *otherLoginWayLab;
// 手动登录
@property (weak, nonatomic) IBOutlet UIView *manualLoginBackView;
@property (weak, nonatomic) IBOutlet UILabel *manualTipLab1;
@property (weak, nonatomic) IBOutlet UILabel *manualTipLab2;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIImageView *showPwdImgView;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *manualLoginBtn;
@property (weak, nonatomic) IBOutlet UIView *lineView1;
@property (weak, nonatomic) IBOutlet UIView *lineView2;
@property (weak, nonatomic) IBOutlet UIView *lineView3;
@property (weak, nonatomic) IBOutlet UIView *changeLoginWayView;
@property (weak, nonatomic) IBOutlet UILabel *codeLoginLab;
@property (weak, nonatomic) IBOutlet UILabel *forgetPwdLab;
@property (weak, nonatomic) IBOutlet UILabel *pwdLoginLab;

@property (nonatomic , assign) BOOL showPwdOpen;
@property (nonatomic , strong) NSString *paramPhone;
@property (nonatomic , strong) NSString *paramCode;
@property (nonatomic , strong) NSString *paramPwd;
@property (nonatomic , strong) NSArray *privacyArr;
@property (nonatomic , strong) NSArray *registerArr;
@property (weak, nonatomic) IBOutlet UILabel *autoLoginLab;

@end

@implementation FPLoginController

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.bubbleTip dismissAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 确保登录页面不显示TabBar
    self.hidesBottomBarWhenPushed = YES;
    
    self.isSelect = NO;
    self.showPwdOpen = NO;
    self.loginType = FPLoginTypeCode;
}

- (void)initUI {
    
    self.bubbleTip = [[JBubbleTips alloc] init];
    self.bubbleTip.text = @"请勾选同意后再登录";
    self.bubbleTip.direction = JBubbleTipsDirectionDown;
    self.bubbleTip.disableDismissWhenTouchInContainer = YES;
    
    [self setTitle:@"" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    self.view.backgroundColor = UIColor.whiteColor;
    [self.selectImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction)]];
    self.privacyLab.textColor = [UIColor hexColor:@"#9A9A9A"];
    
    self.autoLoginBtn.clipsToBounds = YES;
    self.autoLoginBtn.layer.cornerRadius = 22.f;
    self.autoLoginBtn.backgroundColor = MAIN_BLUE_COLOR;
    self.numberLab.textColor = [UIColor hexColor:@"#000000"];
    self.serviceLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.otherLoginWayLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.errorTipPwdLab.textColor = UIColor.redColor;
    self.errorTipPhoneLab.textColor = UIColor.redColor;
    self.errorTipPwdLab.hidden = YES;
    self.errorTipPhoneLab.hidden = YES;
    
    self.manualTipLab1.textColor = [UIColor hexColor:@"#3A3A3A"];
    self.manualTipLab2.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.lineView1.backgroundColor = [[UIColor hexColor:@"#CCCCCC"] colorWithAlphaComponent:.5f];
    self.lineView2.backgroundColor = [[UIColor hexColor:@"#CCCCCC"] colorWithAlphaComponent:.5f];
    self.lineView3.backgroundColor = [[UIColor hexColor:@"#CCCCCC"] colorWithAlphaComponent:.5f];
    self.manualLoginBtn.backgroundColor = MAIN_BLUE_COLOR;
    self.manualLoginBtn.clipsToBounds = YES;
    self.manualLoginBtn.layer.cornerRadius = 22.f;
    self.changeLoginWayView.hidden = YES;
    self.showPwdImgView.hidden = YES;
    self.pwdLoginLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.forgetPwdLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.codeLoginLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.autoLoginLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    
    self.phoneTextField.delegate = self;
    self.codeTextField.delegate = self;
    
    // 切换成一键登录
    [self switchLoginModeAuto];
//    [self switchLoginModeCode];
    
#pragma mark - 一键登录
    [self.autoLoginBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        
        [self.view endEditing:YES];
        
        if (self.isSelect) {
            
            // 一键登录 api
            // ...
        }
        else {
            
//            FPBaseProtocolView *popView = [[FPBaseProtocolView alloc] init];
//            [FPBaseProtocolView showWithText:@"fdafasfasf<flyy>" onAction:^(NSUInteger index) {
//               
//                NSLog(@"%zd",index);
//            }];
            
#warning 协议同意气泡
//            if (!self.bubbleTip.isShowing) {
//             
//                [self.bubbleTip showPointAtView:self.selectImgView animated:YES];
//            }
        }
    }];
    
    // 验证码或 密码登录
    [self.manualLoginBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        
        [self.view endEditing:YES];
        
        if (self.isSelect) {
            
            [self toManualLogin];
        }
        else {
            
            [FPBaseProtocolView showWithText:self.dataSource onAction:^(NSUInteger index) {
                
                if (index == 1001) {
                    
                    // 拒绝
                }
                else {
                    
                    [self selectAction];
                }
                
            } protocolDidSelectAction:^(FPProtocolModel * _Nonnull model) {
                
//                NSLog(@"%@",model.agreementName);
                FPMainWebController *vc = [[FPMainWebController alloc] init];
                vc.model = model;
                vc.protocolType = FPProtocolTypeLogin;
                [self.navigationController pushViewController:vc animated:YES];
            }];
            
//            if (!self.bubbleTip.isShowing) {
//             
//                [self.bubbleTip showPointAtView:self.selectImgView animated:YES];
//            }
        }
    }];
    
    // 获取验证码
    [self.codeBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self.view endEditing:YES];
        [self getSMSCode];
    }];
    
    [self.otherLoginWayLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(switchLoginModeManaul)]];
    [self.pwdLoginLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(switchLoginModePwd)]];
    [self.codeLoginLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(switchLoginModeCode)]];
    [self.forgetPwdLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgetPwdAction)]];
    [self.showPwdImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPasswordAction)]];
    [self.autoLoginLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(autoLoginAction)]];
    
    [self getProtocol];
}

#pragma mark - 点击 登录/注册
- (void)toManualLogin {
    
    if (self.paramPhone.length < 11) {
        
        self.errorTipPhoneLab.hidden = NO;
        [self.phoneTextField shake];
        return;
    }
    else {
        
        self.errorTipPhoneLab.hidden = YES;
    }
    
    if (self.loginType == FPLoginTypeCode) {
        
        if (self.paramCode.length < 4) {
            
            [self.codeTextField shake];
            self.errorTipPwdLab.hidden = NO;
            self.errorTipPwdLab.text = @"验证码有误";
            return;
        }
        else {
            
            [self loginWithSMSCode];
            self.errorTipPwdLab.hidden = YES;
        }
    }
    else {
        
        if (![self isValidPassword:self.paramPwd]) {
            
            self.errorTipPwdLab.hidden = NO;
            [self.codeTextField shake];
            self.errorTipPwdLab.text = @"密码不符合规范";
            return;
        }
        else {
            
            self.errorTipPwdLab.hidden = YES;
            // ... 密码登录
            // ...
        }
    }
    
    
}

- (void)showPasswordAction {
    
    FeedBackGeneratorAction
    
    [self.view endEditing:YES];
    self.showPwdOpen = !self.showPwdOpen;
    self.codeTextField.secureTextEntry = !self.showPwdOpen;
    
    if (self.showPwdOpen) {
     
        self.showPwdImgView.image = IMG(@"icon_pwd_open");
    }
    else {
     
        self.showPwdImgView.image = IMG(@"icon_pwd_close");
    }
}

- (void)selectAction {
    
    FeedBackGeneratorAction
    
//    [self.bubbleTip dismissAnimated:YES];
    
    self.isSelect = !self.isSelect;
    
    if (self.isSelect) {
     
        self.selectImgView.image = SELECT_IMG_BLUE;
    }
    else {
     
        self.selectImgView.image = UNSELECT_IMG;
    }
}

#pragma mark - 忘记密码
- (void)forgetPwdAction {
    
    FPForgetPasswordController *vc = [[FPForgetPasswordController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 设置密码 登录btn 点击之后去设置
- (void)setPwdAction {
    
    FPSetPasswordController *vc = [[FPSetPasswordController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 切换成一键登录
#pragma mark - 暂时没有这个入口 不让返回一键登录
- (void)switchLoginModeAuto {
    
//    self.loginType = FPLoginTypeAutoLogin;
//    self.autoLoginBackView.hidden = NO;
//    self.manualLoginBackView.hidden = YES;
//    [self.bubbleTip dismissAnimated:YES];
//    self.privacyLab.text = @"我已阅读并同意《一键登录渠道协议-接口提供》和《众鑫花注册协议》、《众鑫花隐私政策》";
//    self.errorTipPwdLab.hidden = YES;
//    self.errorTipPhoneLab.hidden = YES;
//    [self analysisProtocol];
    
//    [self initAutoLogin];
}

- (void)autoLoginAction {
    
    [self initAutoLogin];
}



#pragma mark - 切换成手动登录
- (void)switchLoginModeManaul {
    
    self.loginType = FPLoginTypeCode;
    self.autoLoginBackView.hidden = YES;
    self.manualLoginBackView.hidden = NO;
    [self.bubbleTip dismissAnimated:YES];
    
    self.privacyLab.text = @"我已阅读并同意《众鑫花注册协议》、《众鑫花隐私政策》";
    self.codeTextField.placeholder = @"请输入验证码";
    self.phoneTextField.placeholder = @"请输入手机号";
    [self analysisProtocol];
}

#pragma mark - 切换成密码登录
- (void)switchLoginModePwd {
    
    self.loginType = FPLoginTypePassword;
    self.changeLoginWayView.hidden = NO;
    self.codeBtn.hidden = YES;
    self.showPwdImgView.hidden = NO;
    self.codeTextField.placeholder = @"请输入密码";
    self.codeTextField.text = @"";
    self.codeTextField.secureTextEntry = YES;
    self.codeTextField.keyboardType = UIKeyboardTypeDefault;
    self.manualTipLab2.text = @"密码仅可由数字、英文字母或英文符号组成，且需包含其中至少两种类型，长度不少于8个字符";
    self.errorTipPwdLab.hidden = YES;
    self.errorTipPhoneLab.hidden = YES;
    [self analysisProtocol];
}

#pragma mark - 切换成验证码登录
- (void)switchLoginModeCode {
    
    self.loginType = FPLoginTypeCode;
    self.changeLoginWayView.hidden = YES;
    self.showPwdImgView.hidden = YES;
    self.codeBtn.hidden = NO;
    self.codeTextField.placeholder = @"请输入验证码";
    self.codeTextField.text = @"";
    self.codeTextField.secureTextEntry = NO;
    self.codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.manualTipLab2.text = @"登录尊享更多精彩";
    self.errorTipPwdLab.hidden = YES;
    self.errorTipPhoneLab.hidden = YES;
    [self analysisProtocol];
}


#pragma mark - 开始倒计时 验证码
- (void)startCountDownTimer {
    
    [self.view endEditing:YES];
    
    NSDate *oldDate = [NSDate date];
    // 倒计时时间
    __block NSInteger timeOut = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        // 倒计时结束
        if (timeOut <= 0) {
            
            // 再次获取
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.codeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
                self.codeBtn.userInteractionEnabled = YES;
                self.codeBtn.enabled = YES;
                [self.codeBtn setTitleColor:MAIN_BLUE_COLOR forState:(UIControlStateNormal)];
            });
        }
        // 正在倒计时
        else {
            
            NSDate *newDate = [NSDate date];
            NSTimeInterval timeInterva = [newDate timeIntervalSinceDate:oldDate];
            int seconds2 = (60 -timeInterva);
            NSString *timeStr = [NSString stringWithFormat:@"%d",seconds2];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.codeBtn setTitle:[NSString stringWithFormat:@"重新获取(%@)", timeStr] forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = NO;
                self.codeBtn.enabled = NO;
                [self.codeBtn setTitleColor:[UIColor hexColor:@"#999999"] forState:(UIControlStateNormal)];
            });
            //bug 解决
            if (seconds2 <= 1) {
                timeOut = 1;
            }
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}




- (BOOL)isValidPassword:(NSString *)text {
    
    if (text.length < 8) return NO;

    // 只允许数字、字母、符号
    NSString *allowedPattern = @"^[A-Za-z0-9\\p{P}\\p{S}]+$";
    NSRegularExpression *allowedRegex = [NSRegularExpression regularExpressionWithPattern:allowedPattern options:0 error:nil];
    NSUInteger match = [allowedRegex numberOfMatchesInString:text options:0 range:NSMakeRange(0, text.length)];
    if (match == 0) return NO;

    // 判断包含的类型
    BOOL hasDigit = [text rangeOfString:@"\\d" options:NSRegularExpressionSearch].location != NSNotFound;
    BOOL hasLetter = [text rangeOfString:@"[A-Za-z]" options:NSRegularExpressionSearch].location != NSNotFound;
    BOOL hasSymbol = [text rangeOfString:@"[^A-Za-z0-9]" options:NSRegularExpressionSearch].location != NSNotFound;

    int typeCount = (hasDigit ? 1 : 0) + (hasLetter ? 1 : 0) + (hasSymbol ? 1 : 0);
    return typeCount >= 2;
}


#pragma mark - 获取协议
- (void)getProtocol {
    
    [FPProtocolModel getProtocolWithType:(FPProtocolTypeLogin) success:^(NSInteger code, NSString * _Nonnull message, NSArray *list) {
        [MBManager hideLoading];
        
        [self.dataSource removeAllObjects];
        if (code == 200) {
            
            for (FPProtocolModel *model in list) {
                
                [self.dataSource addObject:model];
                
                if ([model.agreementType isEqualToString:@"RegistrationAgreement"]) {
                    
                    self.registerArr = @[model.agreementName , model.address];
                }
                
                if ([model.agreementType isEqualToString:@"PrivacyPolicy"]) {
                    
                    self.privacyArr = @[model.agreementName , model.address];
                }
            }
            
            [self initAutoLogin];
            
            [self analysisProtocol];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [MBManager hideLoading];
    }];
}

- (void)analysisProtocol {
    
    NSMutableString *protocolStr = NSMutableString.string;
    
    for (FPProtocolModel *model in self.dataSource) {
        
        [protocolStr appendFormat:@"%@",model.agreementName];
    }
    
    NSString *text;
    
    if (self.loginType == FPLoginTypeAutoLogin) {
    
        text = [NSString stringWithFormat:@"我已阅读并同意%@%@", @"《中国联通认证服务条款》" , protocolStr];
    }
    else {
        
        text = [NSString stringWithFormat:@"我已阅读并同意%@", protocolStr];
    }
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    for (NSInteger i = 0; i < self.dataSource.count; i ++) {
        
        FPProtocolModel *model = self.dataSource[i];
        
        NSRange range = [text rangeOfString:[NSString stringWithFormat:@"%@", model.agreementName]];
        [NSString stringToAttribute:attStr color:MAIN_BLUE_COLOR range:range];
        
        [self.privacyLab addLinkToURL:[NSURL URLWithString:model.address] withRange:range];
    }
    
    self.privacyLab.attributedText = attStr;
    self.privacyLab.delegate = self;
}

#pragma mark - TTTAttributedLabelDelegate 处理协议点击
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
 
//    [MBManager showText:url.absoluteString];
    for (FPProtocolModel *model in self.dataSource) {
        
        if ([url.absoluteString isEqualToString:model.address]) {
            
            FPMainWebController *vc = [[FPMainWebController alloc] init];
            
            vc.model = model;
            vc.protocolType = FPProtocolTypeLogin;
            
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if ([textField isEqual:self.phoneTextField]) {
        
        self.paramPhone = textField.text;
    }
    else if ([textField isEqual:self.codeTextField]) {
        
        if (self.loginType == FPLoginTypeCode) {
            
            self.paramCode = textField.text;
        }
        else {
            
            self.paramPwd = textField.text;
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ([string isEqualToString:@""]) {
        
        return YES;
    }
    
    // 数字 检查字符串是否为数字
    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    
//    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if ([textField isEqual:self.phoneTextField]) {
        
        if ([string rangeOfCharacterFromSet:nonDigitCharacterSet].location != NSNotFound) {
            
            return NO;  // 如果输入的字符不是数字，则不允许输入
        }
        
        return textField.text.length < 11;
    }
    else if ([textField isEqual:self.codeTextField]) {
    
        if (self.loginType == FPLoginTypeCode) {
        
            if ([string rangeOfCharacterFromSet:nonDigitCharacterSet].location != NSNotFound) {
                
                return NO;  // 如果输入的字符不是数字，则不允许输入
            }
            
            return textField.text.length < 4;
        }
    }
    
    return YES;
}

#pragma mark - 获取验证码
- (void)getSMSCode {
    
    if (self.paramPhone.length != 11) {
        
        FeedBackGeneratorAction
        [self.phoneTextField shake];
        self.errorTipPhoneLab.hidden = NO;
        return;
    }
    
    self.errorTipPhoneLab.hidden = YES;
    
    NSString *number = [FPUserModel AES256Encrypt:self.paramPhone];
    
    [MBManager showLoading];
    [FPUserModel getMessageCodeWithPhoneNumber:number success:^(BOOL isSuccess, NSString * _Nonnull message, NSInteger code) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            [self startCountDownTimer];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 通过验证码登录
- (void)loginWithSMSCode {
    
    NSString *number = [FPUserModel AES256Encrypt:self.paramPhone];
    
    [MBManager showLoading];
    [FPUserModel loginWithPhoneNumber:number code:self.paramCode success:^(FPUserModel * _Nonnull model, NSString * _Nonnull message, NSInteger code , BOOL firstRegist) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessNotification object:@"1"];
            [self signProtocolWithParams:self.dataSource];
            
            UIWindow *keyWindow = [UIApplication sharedApplication].windows.firstObject;
            keyWindow.rootViewController = [[FPMainTabBarController alloc] initWithContext:nil sourcetype:@"userInfo.platformType"];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}





- (void)initAutoLogin {
    
//    [self.bubbleTip dismissAnimated:YES];
    
//    __block BOOL support = YES;
    
//    [[TXCommonHandler sharedInstance] checkEnvAvailableWithAuthType:PNSAuthTypeLoginToken complete:^(NSDictionary * _Nullable resultDic) {
//        
//        support = [PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]];
//    }];
    
//    [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:timeout complete:^(NSDictionary * _Nonnull resultDic) {
//        if ([PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]] == NO) {
////            [ProgressHUD showError:@"取号，加速授权页弹起失败"];
////            [weakSelf showResult:resultDic];
//            return ;
//        }];
        
        
    /*
     *  @param  screenSize 屏幕的size，可以通过该size来判断是横屏还是竖屏
     *  @param  superViewSize 该控件的super view的size，可以通过该size，辅助该控件重新布局
     *  @param  frame 控件默认的位置
     *  @return 控件新设置的位置
     我已阅读并同意《一键登录渠道协议-接口提供》和《众鑫花注册协议》、《众鑫花隐私政策》
     */
    // https://help.aliyun.com/zh/pnvs/developer-reference/the-ios-client-access?spm=a2c4g.11186623.help-menu-75010.d_5_1_1_1.63de5c20rsYW54
    TXCustomModel *model = [[TXCustomModel alloc] init];
    model.prefersStatusBarHidden = NO;
    model.navColor = UIColor.whiteColor;
    model.logoImage = IMG(@"launch_logo");
    
    NSMutableAttributedString *att1 = [[NSMutableAttributedString alloc] initWithString:@"本机号码一键登录"];
    [NSString stringToAttribute:att1 color:UIColor.whiteColor range:NSMakeRange(0, att1.length)];
    model.loginBtnText = att1;
    
    NSMutableAttributedString *att2 = [[NSMutableAttributedString alloc] initWithString:@"其他号码登录"];
    [NSString stringToAttribute:att2 color:[UIColor hexColor:@"#6A6A6A"] range:NSMakeRange(0, att2.length)];
    model.changeBtnTitle = att2;
    
//    model.changeBtnIsHidden = NO;
    
    model.privacyOperatorPreText = @"《";
    model.privacyOperatorSufText = @"》";
    model.privacyOperatorColor = MAIN_BLUE_COLOR;
    model.privacyOneColor = MAIN_BLUE_COLOR;
    model.privacyTwoColor = MAIN_BLUE_COLOR;
    model.changeBtnFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        
        return CGRectMake(10, frame.origin.y - 50, SCREEN_WIDTH - 20, 60);
    };
    
    for (FPProtocolModel *m in self.dataSource) {
        
        if ([m.agreementType isEqualToString:@"RegistrationAgreement"]) {
            
            model.privacyOne = @[m.agreementName , m.address];
        }
        
        if ([m.agreementType isEqualToString:@"PrivacyPolicy"]) {
            
            model.privacyTwo = @[m.agreementName , m.address];
        }
    }
    
    
    [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:3.f controller:self model:model complete:^(NSDictionary * _Nonnull resultDic) {
            
//            NSUInteger code = [[resultDic objectForKey:@"resultCode"] integerValue];
//
//            if (code == 600000) {
//
//                // 调用成功
//            }
//            else if (code == 700000) {
//
        //                // 用户取消 返回
        //            }
            
        self.autoLoginLab.hidden = NO;
        
        NSString *code = [resultDic objectForKey:@"resultCode"];
        
        if ([PNSCodeGetOperatorInfoFailed isEqualToString:code] || /// 获取运营商配置信息失败
            [PNSCodeNoSIMCard             isEqualToString:code] || /// 未检测到sim卡
            [PNSCodeNoCellularNetwork     isEqualToString:code] || /// 蜂窝网络未开启或不稳定
            [PNSCodeUnknownOperator       isEqualToString:code] || /// 无法判运营商
            [PNSCodeUnknownError          isEqualToString:code] || /// 未知异常
            [PNSCodeGetTokenFailed        isEqualToString:code] || /// 获取token失败
            [PNSCodeGetMaskPhoneFailed    isEqualToString:code] || /// 预取号失败
            [PNSCodeInterfaceDemoted      isEqualToString:code] || /// 运营商维护升级，该功能不可用
            [PNSCodeInterfaceLimited      isEqualToString:code] || /// 运营商维护升级，该功能已达最大调用次数
            [PNSCodeInterfaceTimeout      isEqualToString:code] || /// 接口超时
            [PNSCodeDecodeAppInfoFailed   isEqualToString:code] || /// AppID、Appkey解析失败
            [PNSCodePhoneBlack            isEqualToString:code] || /// 该号码已被运营商管控,目前只有联通号码有该功能
            [PNSCodeCarrierChanged        isEqualToString:code] || /// 运营商已切换
            [PNSCodeEnvCheckFail          isEqualToString:code]) { /// 终端环境检测失败（终端不支持认证 / 终端检测参数错误）
            
//            [self showText:@""];
            self.autoLoginLab.hidden = YES;
        }
        else if ([PNSCodeLoginControllerPresentSuccess isEqualToString:code]) {
            NSLog(@"弹起授权页成功");
        } else if ([PNSCodeLoginControllerClickCancel isEqualToString:code]) {
            NSLog(@"点击了授权页的返回");
        }
        else if ([PNSCodeLoginControllerClickChangeBtn isEqualToString:code]) {
           
            // 切换其他登录
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:^{
            }];
//                [ProgressHUD showSuccess:@"点击切换其他登录方式按钮"];
       } 
        else if ([PNSCodeLoginControllerClickLoginBtn isEqualToString:code]) {
            if ([[resultDic objectForKey:@"isChecked"] boolValue] == YES) {
//                    [ProgressHUD showSuccess:@"点击了登录按钮，check box选中，SDK内部接着会去获取登录Token"];
            } else {
//                    [ProgressHUD showSuccess:@"点击了登录按钮，check box未选中，SDK内部不会去获取登录Token"];
            }
        } else if ([PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:code]) {
//                [ProgressHUD showSuccess:@"点击check box"];
        } else if ([PNSCodeLoginControllerClickProtocol isEqualToString:code]) {
//                [ProgressHUD showSuccess:@"点击了协议富文本"];
        } else if ([PNSCodeSuccess isEqualToString:code]) {
            //点击登录按钮获取登录Token成功回调
            NSString *token = [resultDic objectForKey:@"token"];
            
            [MBManager showLoading];
            [FPUserModel loginWithAccessToken:token success:^(NSString * _Nonnull message, NSInteger code , BOOL firstRegist) {
                [MBManager hideLoading];
                
                if (code == 200) {
                    
                    [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:^{
                                
                                [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessNotification object:nil];
                                [self.navigationController popViewControllerAnimated:YES];
                            }];
                        });
                        
                    } failure:^(NSError * _Nonnull error) {
                        
                    }];
                }
                else {
                    
                    [self showText:message];
                }
                
            } failure:^(NSError * _Nonnull error) {
                [self showError:error];
            }];
            
//                //下面用Token去服务器换手机号，此处仅做参考
//                [PNSVerifyTopRequest requestLoginWithToken:token complete:^(BOOL isSuccess, NSString * _Nonnull msg, NSDictionary * _Nonnull data) {
//                    NSString *popCode = [data objectForKey:@"code"];
//                    NSDictionary *module = [data objectForKey:@"module"];
//                    NSString *mobile = module[@"mobile"];
//                    if ([popCode isEqualToString:@"OK"] && mobile.length > 0) {
//                        [ProgressHUD showSuccess:@"一键登录成功"];
//                    } else {
//                        [ProgressHUD showSuccess:@"一键登录失败"];
//                    }
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
//                    });
//                    [weakSelf showResult:data];
//                }];
        }
        else {
//                [ProgressHUD showError:@"获取登录Token失败"];
        }
//            [weakSelf showResult:resultDic];
    }];
    
//    [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:3.f complete:^(NSDictionary * _Nonnull resultDic) {
//
//        if ([PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]] == NO) {
//            //            [ProgressHUD showError:@"取号，加速授权页弹起失败"];
//            //            [weakSelf showResult:resultDic];
//            return;
//        }
//    }];
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    
    
    

    
    /**
     if ([operator isEqualToString:@"CU"]) {
         
         self.operatorsType = XYOperatorsTypeCU;
         self.seviceTipLab.text = @"中国联通提供认证服务";
         text = @"登录即同意《中国联通认证服务条款》和《平台用户服务协议》和《隐私政策》并使用本机号码登录。";
         url = [NSURL URLWithString:@"protocol_CU"];
     }
     else if ([operator isEqualToString:@"CT"]) {
         
         self.operatorsType = XYOperatorsTypeCT;
         self.seviceTipLab.text = @"中国电信提供认证服务";
         text = @"登录即同意《中国电信认证服务条款》和《平台用户服务协议》和《隐私政策》并使用本机号码登录。";
         url = [NSURL URLWithString:@"protocol_CT"];
     }
     else if ([operator isEqualToString:@"CM"]) {
         
         self.operatorsType = XYOperatorsTypeCM;
         self.seviceTipLab.text = @"中国移动提供认证服务";
         text = @"登录即同意《中国移动认证服务条款》和《平台用户服务协议》和《隐私政策》并使用本机号码登录。";
         url = [NSURL URLWithString:@"protocol_CM"];
     }
     else {
         
         NSLog(@"认证出错了");
         self.operatorsType = XYOperatorsTypeUnknow;
         text = @"登录即同意《运营商的认证服务条款》和《平台用户服务协议》和《隐私政策》并使用本机号码登录。";
         url = [NSURL URLWithString:@"protocol_faild"];
     }
     */
}


@end
